<?php


namespace PKFrame\Driver;
defined('PATH_PK') or die();

use PKFrame\DataHandler\Arrays;
use PKFrame\DataHandler\JSON;

class PDO_MySQL
{

    private $_config, $_index;
    public $version = 0;

    public function __construct($config, int $index = 0)
    {
        $this->_config = $config;
        $this->_index = $index;
    }

    private function _notice(\Exception $exception)
    {
        out()->noticeByJson($exception->getMessage());
    }

    public function Conn($is_connectDB = true): ?\PDO
    {
        try {
            if ($is_connectDB) {
                $conn_str = 'mysql:host=' . $this->_config['host'];
            } else {
                $conn_str = 'mysql:host=' . $this->_config['host'] . ';dbname=' . $this->_config['name'];
            }
            $params = [
                //设置编码
                \PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8mb4",
                //使用预处理
                \PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $conn = new \PDO($conn_str, $this->_config['user'], $this->_config['pass'], $params);
            $conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (\Exception $e) {
            logger()->ERROR($e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine());
            out()->noticeByJson(language('DataBase_Connect_Error'));
        }
        return null;
    }

    private function _errorLog(\PDO $conn, $sqlStr)
    {
        logger()->LOGS(JSON::EnCode($conn->errorInfo()), array('sql' => $sqlStr, 'ErrorCode' => $conn->errorCode()));
    }

    public function sqlQuery($sqlStr, int $index = 0)
    {
        !empty($sqlStr) ?: out()->noticeByJson('do sql is empty');
        $conn = $this->Conn();
        try {
            $conn->exec($sqlStr);
        } catch (\PDOException $exception) {
            $this->_errorLog($conn, $sqlStr);
            $this->_notice($exception);
        }
    }

    public function fetchAssoc($sqlStr, $toList = false, int $index = 0)
    {
        !empty($sqlStr) ?: out()->noticeByJson('do sql is empty');
        $result = '';
        $conn = $this->Conn();
        if ($toList) {
            $sth = $conn->query($sqlStr);
            $result = $sth->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            $sth = $conn->query($sqlStr);
            $result = $sth->fetch(\PDO::FETCH_ASSOC);
        }
        return $result;
    }

    public function insert($sqlStr, int $index = 0)
    {
        !empty($sqlStr) ?: out()->noticeByJson('do sql is empty');
        $conn = $this->Conn();
        try {
            if (Arrays::Is($sqlStr)) {
                $conn->exec(implode(';', $sqlStr));
            }
        } catch (\PDOException $exception) {
            $this->_errorLog($conn, $sqlStr);
            $this->_notice($exception);
        }
    }

    public function insertId($sqlStr, int $index = 0)
    {
        !empty($sqlStr) ?: out()->noticeByJson('do sql is empty');
        $id = 0;
        $conn = $this->Conn();
        try {
            $conn->exec($sqlStr);
            $id = $conn->lastInsertId();
        } catch (\PDOException $exception) {
            $this->_errorLog($conn, $sqlStr);
            $this->_notice($exception);
        }
        return $id;
    }
}
